<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>LyApi Maker - 接口创造器</title>
  <link rel="stylesheet" href="{{domain}}/resource/admin/mini/lib/layui-v2.5.5/css/layui.css" media="all">

  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  <script src="{{domain}}/resource/admin/mini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
  <script src="{{domain}}/resource/admin/maker/js/Sortable.min.js" charset="utf-8"></script>
</head>

<body>
  <ul class="layui-nav layui-bg-green" lay-filter="">
    <li class="layui-nav-item">
      <a href="javascript:;">模板</a>
      <dl class="layui-nav-child">
        <!-- 二级菜单 -->
        <dd><a href="javascript:;" onclick="">新建模板</a></dd>
        <dd><a href="{{domain}}/admin#//admin/page?type=template&which=list">组件列表</a></dd>
      </dl>
    </li>
    <li class="layui-nav-item">
      <a href="javascript:;">组件</a>
      <dl class="layui-nav-child">
        <!-- 二级菜单 -->
        <dd><a href="javascript:;" id="new-comp">新建组件</a></dd>
        <dd><a href="javascript:;">组件仓库</a></dd>
      </dl>
    </li>
    <li class="layui-nav-item"><a href="http://bbs.wwsg18.com/t/talk" target="_bank">开发社区</a></li>
  </ul><br>

  <div class="layui-row">
    <div class="layui-col-md1">&nbsp;</div>
    <div class="layui-col-md4">

      <fieldset class="layui-elem-field">
        <legend>模板程序组件列表</legend>
        <div class="layui-field-box">
          <div class="layui-collapse" id="comp-list" style="min-height: 42px;">
          </div><br />
          <div>
            <div class="layui-btn-group">
              <button type="button" class="layui-btn layui-btn-normal" id="save-tpl">
                保存模板
              </button>
              <button type="button" class="layui-btn" id="create-api">
                创建接口
              </button>
              <button type="button" class="layui-btn layui-btn-danger" id="clean-all">
                清空模板
              </button>
            </div>
          </div>
        </div>
      </fieldset>

      <!-- 组件信息模板（用于内容复制） -->
      <div id="comp-template" style="display: none;">
        <div class="layui-colla-item" id="COMP-[sign]">
          <h2 class="layui-colla-title" style="background-color: #5FB878;color:white;">[title]</h2>
          <div class="layui-colla-content">
            [data]
          </div>
        </div>
      </div>

    </div>
    <div class="layui-col-md1">&nbsp;</div>
    <div class="layui-col-md5">

      <fieldset class="layui-elem-field">
        <legend>组件选择加载</legend>
        <div class="layui-field-box">

          <form class="layui-form" action="">
            <div class="layui-form-item">
              <select name="ctype" id="ctype" lay-filter="ctype">
                <option value="">请选择组件类型</option>
                {{# comps}}
                <option value="{{sign}}">{{name}} ({{sign}})</option>
                {{/ comps}}
              </select>
            </div>
            <hr class="layui-bg-black">
            <div id="forms"></div>

            <div class="layui-form-item">
              <button class="layui-btn" lay-submit lay-filter="next">下一步</button>
            </div>

          </form>

        </div>
      </fieldset>

      <fieldset class="layui-elem-field">
        <legend>组件回收站（不需要的组件拖入这里）</legend>
        <div class="layui-field-box">
          <div class="layui-collapse" id="trash-list" style="min-height: 126px;">
          </div><br />
          <button type="button" class="layui-btn layui-btn-danger" id="cleanTrash">清空回收站</button>
        </div>
      </fieldset>

    </div>
    <div class="layui-col-md1">&nbsp;</div>
  </div>



  <script>
    layui.use(['element', 'form', 'layer'], function () {
      var element = layui.element,
        layer = layui.layer,
        form = layui.form;

      // 加载组件列表
      $.get('{{domain}}/admin/api/maker/comps?all&from=maker', function (res) {
        if (res.code == '200' && res.msg == '') {
          for (var index in res.data) {
            var template = $('#comp-template').html();

            template = template.replace('[sign]', res.data[index].code);

            template = template.replace('[title]', res.data[index].name + ' [' +
              res.data[index].code + ']');

            var used = res.data[index].used;
            if (used == '') {
              used = 'NULL';
            }

            template = template.replace('[data]', "<ul><li>组件标识: " +
              res.data[index].code + "</li><li>函数名称: " +
              res.data[index].func + "</li><li>引入模块: " +
              used + "</li></ul>");

            $('#comp-list').append(template);
          }
          element.render('collapse');
        } else {
          layer.msg('接口异常: ' + res.msg);
        }
      });


      form.on('select(ctype)', function (data) {
        $.get('{{domain}}/admin/api/maker/component?do=form&name=' + data.value, function (res) {
          if (res.msg == '' && res.code == "200") {
            $('#forms').html("");
            for (var index in res.data) {
              var v = res.data[index];
              var code = '<div class="layui-form-item">'

              // 根据不同类型生成表单
              if (v.label == 'input') {
                var items = '';

                for (var item in v) {
                  if (item != 'label') {
                    items += item + '="' + v[item] + '" ';
                  }
                }

                code += '<input ' + items + ' class="layui-input">';
              } else if (v.label == 'select') {
                var items = '';

                for (var item in v) {
                  if (item != 'label' && item != 'child' && item != 'info') {
                    items += item + '="' + v[item] + '" ';
                  }
                }

                code += '<select lay-verify="required" ' + items + '>';

                if (v.hasOwnProperty('info')) {
                  code += '<option value="">' + v.info + '</option>';
                }

                for (var child in v.child) {
                  code += '<option value="' + child + '">' + v.child[child] + '</option>';
                }

                code += '</select>';
              } else if (v.label == 'textarea') {

                var items = '';

                for (var item in v) {
                  if (item != 'label') {
                    items += item + '="' + v[item] + '" ';
                  }
                }

                code += '<textarea ' + items + ' class="layui-textarea"></textarea>';

              } else if (v.label == 'info') {

                var items = '';

                for (var item in v) {
                  if (item != 'label') {
                    items += item + '="' + v[item] + '" ';
                  }
                }

                code += '<span ' + items + '>' + v['value'] + '</span>';
              }

              code += "</div>"
              $('#forms').append(code);
            }
            form.render();
          } else {
            layer.msg('组件表单加载失败...');
          }
        });
      });

      // 清空回收站组件
      $('#cleanTrash').click(function () {

        // 判定回收站是否为空

        if ($('#trash-list').html().trim().length !== 0) {

          // 询问用户是否确定清空 (真的很危险！！)
          layer.confirm('清空后模板内容将同步删除，是否确定？', {
            btn: ['确定', '取消']
          }, function (index) {
            // 清除所有数据操作
            layer.close(index);
            console.log($('#trash-list').children());

            var childs = $('#trash-list').children();
            for (var key in childs) {
              // 取得子标签的ID
              var cid = childs[key].id;

              if (cid != undefined) {
                var sign = cid.substring(cid.length - (13 - 5), cid.length);
                // 发起删除 sign 请求
                $.get("{{domain}}/admin/api/maker/comps?do=del&sign=" + sign, function (res) {
                  if (res.data == 'OK') {
                    console.log('#COMP-' + sign + ' 删除成功！');
                    $('#COMP-' + sign).remove();
                  } else {
                    layer.msg('[' + sign + '] 删除失败！');
                  }
                });
              }
            }
          });

        }
      });

      form.on('submit(next)', function (data) {
        // layer.msg(JSON.stringify(data.field));

        if (data.field.ctype != '') {
          $.get('{{domain}}/admin/api/maker/component?do=secc&name=' + data.field.ctype, function (res) {

            if (isJSON(res)) {
              // 处理弹出框程序
              res = JSON.parse(res);
              if (res.type == 'prompt') {
                layer.prompt({
                  title: res.title,
                }, function (value, index, elem) {
                  data.field[res.name] = value;
                  layer.close(index);

                  // 立刻发起模板新增请求
                  var url = '{{domain}}/admin/api/maker/managers'
                  $.post(url, {
                    comp: data.field.ctype,
                    data: JSON.stringify(data.field)
                  }, function (res) {
                    if (res.data == 'OK') {
                      window.location.reload();
                    }
                  });
                });
              }

            } else if (res != 'no-console') {
              layer.open({
                type: 2,
                title: '[' + data.field.ctype + '] 组件控制台',
                shadeClose: true,
                shade: false,
                maxmin: true, //开启最大化最小化按钮
                area: ['800px', '560px'],
                content: '{{domain}}/admin/api/maker/component?do=secc&name=' + data.field.ctype + '&' +
                  $.param(data.field)
              });
            } else {
              // 立刻发起模板新增请求
              var url = '{{domain}}/admin/api/maker/managers'
              $.post(url, {
                comp: data.field.ctype,
                data: JSON.stringify(data.field)
              }, function (res) {
                if (res.data == 'OK') {
                  window.location.reload();
                }
              });
            }
          });
        } else {
          layer.msg('您还未选择任何的组件...');
        }

        return false;
      });

      // 按钮点击操作事件

      $('#new-comp').click(function () {
        layer.msg('当前版本暂不支持在线组件创建...');
      });

      $('#clean-all').click(function () {
        cleanAll();
      });

      $('#create-api').click(function () {
        // 
        layer.open({
          type: 2,
          title: '新建接口 #Maker#',
          shadeClose: true,
          shade: false,
          area: ['720px', '480px'],
          content: '{{domain}}/admin/page?type=apis&which=list.add&maker=t'
        });
      });

      $('#save-tpl').click(function () {
        var tname = '';
        var ttype = '';

        layer.prompt({
          title: '请输入模板名称: 名称[类型]',
        }, function (data, index) {
          // 解析数据
          var patt = /(.*)\[(VIEW|API)\]/i
          // console.log(patt.exec(data));
          var ds = patt.exec(data);
          if (ds != null) {
            tname = ds[1];
            ttype = ds[2];
          } else {
            tname = data;
            ttype = 'API';
          }

          layer.close(index);

          if (tname != '' && ttype != '') {
            $.post('{{domain}}/admin/api/maker/newTpl', {
              tname: tname,
              ttype: ttype
            }, function (res) {
              if(res.code == '200'){
                layer.msg('新建模板成功...');
              }else{
                layer.msg(res.msg + "!");
              }
            }).fail(function(res){
              layer.msg('操作异常：' + res.responseJSON.msg + '！');
            });
          }
        });

      });

      function cleanAll() {
        layer.confirm('本操作将清空所有的组件信息，是否继续？', {
          btn: ['继续', '取消']
        }, function () {
          $.get('{{domain}}/admin/api/maker/comps?do=clean&from=maker');
          location.reload();
        });
      }

    });

    function isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          return false;
        }
      }
    }

    var compList = document.getElementById("comp-list");
    Sortable.create(compList, {
      group: "component"
    });

    var compList = document.getElementById("trash-list");
    Sortable.create(compList, {
      group: "component"
    });
  </script>
</body>

</html>